package com.gem.taskplan.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.gem.taskplan.service.BackAcitvity;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.JsonPackage;
import com.gem.taskplan.util.ClassTools;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.bitmap.core.BitmapCache;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class EditUserActivity extends Activity {
	private String url = "/RegisterServlet";
	private String pictureUrl = "/UploadingServlet";
	private ImageView backImageView = null;
	private EditText userName = null;
	private TextView sexPerson = null;
	private EditText photo = null;
	private TextView registerTime = null;
	private TextView finidhPersonEdit = null;
	private EditText email = null;
	private ImageView userHead = null;
	private LinearLayout userMale = null;
	private LinearLayout userFemale = null;
	private TextView userSexMale = null;
	private TextView userSexFemale = null;
	private RelativeLayout userSexEdit = null;
	private FinalBitmap fb ;
	private final String USER_HEAD_NAME = "userHead";
	private String curUser;
	 String[] value ;
	 private LayoutInflater inflater;
	 private View editUserInfo;
	 
	 /*组件*/
		private RelativeLayout editUserHead;
//		private ImageView userInfoHead;
		private String[] items = new String[] { "选择本地图片", "拍照" };
		/*头像名称*/
		private static final String IMAGE_FILE_NAME = "faceImage.jpg";
		/* 请求码*/
		private static final int IMAGE_REQUEST_CODE = 0;
		private static final int CAMERA_REQUEST_CODE = 1;
		private static final int RESULT_REQUEST_CODE = 2;
		private String urlPhoto = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_user);
		
		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);
		
		/************获得访问服务器的地址***************/
		url = PropertiesUtil.getServerURL(this)+url;
		pictureUrl = PropertiesUtil.getServerURL(this)+pictureUrl;
		curUser = getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE).getString("lastUser", "");
//		Toast.makeText(this, curUser,Toast.LENGTH_SHORT).show();
		
		/***************************************/
		inflater = getLayoutInflater();
		inintView();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		value = bundle.getStringArray("userInfo");
		fb = FinalBitmap.create(EditUserActivity.this);
		fb.clearCache();
		inintUserDate();
		
		System.out.println("-----------------------------------------------------------");
		editUserHead.setOnClickListener(listener);
		userSexEdit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				editUserInfo = inflater.inflate(R.layout.edit_user_sex_dialog, null);
				userMale = (LinearLayout) editUserInfo.findViewById(R.id.userMale);
				userFemale = (LinearLayout) editUserInfo.findViewById(R.id.userFemale);
				userSexMale = (TextView) editUserInfo.findViewById(R.id.userSexMale);
				userSexFemale = (TextView) editUserInfo.findViewById(R.id.userSexFemale);
				final AlertDialog dialog = new AlertDialog.Builder(EditUserActivity.this).setView(editUserInfo)
						.create();
				dialog.show();
				userMale.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						sexPerson.setText(userSexMale.getText().toString());
						dialog.cancel();
					}
				});
				userFemale.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						sexPerson.setText(userSexFemale.getText().toString());
						dialog.cancel();
					}
				});
			}
		});
		
		finidhPersonEdit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*if (urlPhoto!=null) {
					new BitmapCache(null).clearCache();
				}*/
				upLoadingUserHead();
				inintHttp();
			}
		});
		BackAcitvity.back(backImageView, EditUserActivity.this);
	}
	/****************************初始化控件*********************************/
	public void inintView(){
		
		backImageView = (ImageView)findViewById(R.id.backImage);//返回按钮
		userName = (EditText) this.findViewById(R.id.loginNameET);//用户名
		userHead = (ImageView) findViewById(R.id.userInfoHead);//用户头像
		sexPerson = (TextView) findViewById(R.id.sexPerson);//性别
		photo = (EditText) findViewById(R.id.photoET);//手机号
		email = (EditText) findViewById(R.id.emailET);//用户邮箱
		userSexEdit = (RelativeLayout) findViewById(R.id.userSexEdit);
		registerTime = (TextView) findViewById(R.id.registerTime);//注册时间
		finidhPersonEdit = (TextView) findViewById(R.id.finidhPersonEdit);//完成按钮
		editUserHead = (RelativeLayout) findViewById(R.id.editUserHead);//编辑头像按钮
	}
	/****************************初始化从上个界面传过来的用户数据*********************************/
	public void inintUserDate(){
		fb.closeCache();
		fb.display(userHead, value[0]);
		userName.setText(value[1]);
		sexPerson.setText(value[2]);
		email.setText(value[3]);
		photo.setText(value[4]);
		registerTime.setText(value[5]);
	}
	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			showDialog();
		}
	};
	/*******************************上传头像*********************************/
	private void upLoadingUserHead(){
		
		/*********判断是否联网***************/
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		
		AjaxParams params1 = new AjaxParams();
		params1.put("action", "updateUserHead");
		params1.put("userName", curUser);
		try {
			params1.put("user_picture", new File(urlPhoto));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 上传文件
		
		
		FinalHttp fh = new FinalHttp();
		fh.post(pictureUrl, 
				params1, new AjaxCallBack<String>(){
			@Override
			public void onSuccess(String t) {
				Toast.makeText(EditUserActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
				super.onSuccess(t);
			}
			@Override
			public void onFailure(Throwable t, String strMsg) {
				Toast.makeText(EditUserActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
				super.onFailure(t, strMsg);
			}
		}); 
	}
	/**
	 * 显示选择对话框
	 */
	private void showDialog() {
		new AlertDialog.Builder(this)
		.setTitle("设置头像")
		.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					System.out.println("选择图库————————————————————————————");
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery
					.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery,
							IMAGE_REQUEST_CODE);
					break;
				case 1:
					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					// 判断存储卡是否可以用，可用进行存储
					if (ClassTools.hasSdcard()) {
						intentFromCapture.putExtra(
								MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(Environment
										.getExternalStorageDirectory()+File.separator+"DCIM",
										IMAGE_FILE_NAME)));
					}
					System.out.println("选择拍照————————————————————————————");
					startActivityForResult(intentFromCapture,
							CAMERA_REQUEST_CODE);
					break;
				}
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode!= RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				System.out.println("图库回调————————————————————");
				System.out.println("调用截图方法——————————————————————————————");
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				System.out.println("拍照回调————————————————————");
				if (ClassTools.hasSdcard()) {
					File tempFile = new File(
							Environment.getExternalStorageDirectory().toString()+File.separator+"DCIM"+File.separator
							+ IMAGE_FILE_NAME);

					System.out.println("调用截图方法——————————————————————————————");
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(EditUserActivity.this, "未找到存储卡，无法存储照片！",
							Toast.LENGTH_LONG).show();
				}
				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			}
			super.onActivityResult(requestCode, resultCode, data);
		}  
	} 
	/**
	 * 裁剪图片方法实现
	 *  
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		System.out.println("图片路径----"+uri);
		System.out.println("图片路径----"+uri.toString());
		//urlPhoto = uri.getPath();
		//System.out.println("图片路径----"+urlPhoto);
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 500);
		intent.putExtra("outputY", 500);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}
	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			try {
				Map<String, String> map = new HashMap<String, String>();
				map.put("userName", curUser);
				map.put("action", "getUserId");
				String result = null;
				String pictureName = null;
				/*********判断是否联网***************/
				if(!CheckedNetWork.checkedConnection(this)){
					return;
				}
				
				result = HttpUtil.postRequest(pictureUrl, map);
				if (result==null) {
//					Toast.makeText(EditUserActivity.this, "您的网络异常！", Toast.LENGTH_SHORT).show();
					return;
				}else if (result.equals("no")) {
//					Toast.makeText(EditUserActivity.this, "没有查到ID！", Toast.LENGTH_SHORT).show();
					return;
				}else {
					pictureName = USER_HEAD_NAME+result+".PNG";
				}
				
				File file = new File(Environment.getExternalStorageDirectory().toString()+File.separator+"DCIM"+File.separator+"taskPlan"+File.separator+pictureName);
				urlPhoto = file.getPath();
				System.out.println("444444444444444");
				System.out.println(urlPhoto);
				if(!file.getParentFile().exists()){
					file.getParentFile().mkdirs();
				}
				OutputStream out = new FileOutputStream(file);
				photo.compress(Bitmap.CompressFormat.PNG, 90, out);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			System.out.println("图片流"+photo.toString());
			Drawable drawable = new BitmapDrawable(photo);
			userHead.setImageDrawable(drawable);
		}
	}  
	private void inintHttp(){
		String[] key = new String[]{"user_picture","user_name","user_sex","user_email","user_phone"};
		String userNamesString = userName.getText().toString();
		String phonesString = photo.getText().toString();
		String sex = sexPerson.getText().toString();
		String emailsString = email.getText().toString(); 
		String[] editValue = new String[]{"",userNamesString,sex,emailsString,phonesString};
		String jsonString = JsonPackage.getJson("userListJson", editValue, key);
		System.out.println("----------:::::::   "+jsonString);
		Map<String, String> map = new HashMap<String, String>();
		map.put("oldUserName", curUser);
		map.put("newUserName", userName.getText().toString());
		map.put("editUserInfo",jsonString);
		map.put("action","updateUserInfo");
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("________编辑用户信息，来自EditUserActivity：————————"+result);
		if (result.equals("yes")) {
			Intent intent = new Intent(EditUserActivity.this,UserActivity.class);
			intent.putExtra("newUserName", userName.getText().toString());
			setResult(1, intent);
			Toast.makeText(EditUserActivity.this, "用户信息修改成功！", Toast.LENGTH_SHORT).show();
			finish();
		}else if (result.equals("no1")) {
			Toast.makeText(EditUserActivity.this, "用户名已存在！", Toast.LENGTH_SHORT).show();
			return;
		}else{
//			Toast.makeText(EditUserActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();
			return;
		}
	}
}
